﻿//选择用户
(function(){
	var $usermodal = $("#selectuser-modal"),
		$userbody = $usermodal.find(".modal-body");

	//遍历选中用户
	$usermodal.on("show.bs.modal",function(){
		var $checkeduser = $(".users-input").val();
		if($checkeduser!=""){
			$checkeduser = $checkeduser.split(",");
			$(this).find(".user-checkbox").each(function(){
				var $user = $(this).parent("label").text();
				for(var i=0;i<$checkeduser.length;i++){
					if($user==$checkeduser[i]){
						$(this).prop("checked",true);
					}
				}
			});
		}
	});

	//滚动条返回顶部
	$usermodal.on("shown.bs.modal",function(){
		$(this).scrollTop(0);
	});

	//用户全选
	$('body').on("click",".all-checkbox",function(){
		if($(this).prop("checked")){
			$usermodal.find(".user-checkbox:enabled,.department-checkbox").prop("checked",true);
		}else{
			$usermodal.find(".user-checkbox:enabled,.department-checkbox").prop("checked",false);
		}
	});

	//部门全选
	$('body').on("click",".department-checkbox",function(){
		var $ul = $(this).parents(".department").next("ul");
		if($(this).prop("checked")){
			$ul.find(".user-checkbox:enabled").prop("checked",true);
		}else{
			$ul.find(".user-checkbox:enabled").prop("checked",false);
			$usermodal.find(".all-checkbox").prop("checked",false);
		}
	});

	//用户单选
	$('body').on("click",".user-checkbox",function(){
		if(!$(this).prop("checked")){
			$(this).parents("ul").prev(".department").find(".department-checkbox").prop("checked",false);
			$usermodal.find(".all-checkbox").prop("checked",false);
		}
	});

	//确定选择用户
	$('body').on("click",".user-affirm",function(){
		var $usersub = false;
		$usermodal.find(".user-checkbox").each(function(){
			if($(this).prop("checked")){
				$usersub = true;
				return false;
			}
		});
		if($usersub){
			var $users = "",
				$uids = "";
			$usermodal.find(".user-checkbox").each(function(){
				if($(this).prop("checked")){
					$users += $(this).parent("label").text()+",";
					$uids += $(this).val()+",";
				}
			}); 
			
			$users = $users.replace(/\,$/,"");
			$uids = $uids.replace(/\,$/,"");
			$(".users-list").html("<strong>已选用户：</strong>"+$users);
			$(".users-input").val($users);
			$(".uids-input").val($uids);
			$usermodal.modal("hide");
		}else{
			$("body").append("<div class='success-defeated hide'>至少选择一位用户</div>");
		    var defeated = $(".success-defeated"),
		    	t = -defeated.outerHeight()/2,
		        l = -defeated.outerWidth()/2;
		   	defeated.css({"margin-top":t,"margin-left":l}).slideDown();
		    setTimeout(function(){
		    	defeated.remove();
		    },2000);
		}
	});

	//取消选择用户
	$usermodal.on("hidden.bs.modal",function(){
		$(this).find(":checkbox").prop("checked",false);
	});
})();